package com.intelligentmeterreadingsys.waterlist.reviewdata.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.intelligentmeterreadingsys.R;
import com.intelligentmeterreadingsys.httpserver.HttpClientServer;
import com.intelligentmeterreadingsys.httpserver.RequestUrl;
import com.intelligentmeterreadingsys.util.FileNameUtil;
import com.intelligentmeterreadingsys.util.SharedPreferenceUtil;
import com.intelligentmeterreadingsys.waterlist.db.WaterListDaoImpl;
import com.intelligentmeterreadingsys.waterlist.reviewdata.db.ReviewDataDao;

import dbhelper.DbTableName;
import dbhelper.XmlNameHelper;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

/**
 * 复查数据管理主界面
 * @author king
 *
 */
public class ReviewMainActivity extends Activity implements OnClickListener{
	private final static int DIALOG=1;
	public Button button1;//复查数据
	public Button button2;//复查数据查询
	public Button button3;//复查数据上传
	public Button button4;//复查数据下载
	public int watertotal=0;
	public SharedPreferenceUtil sp=null;
	public WaterListDaoImpl dao=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    
		super.onCreate(savedInstanceState);
		setContentView(R.layout.review_main);
		init();
	}

	//初始化控件
	public void init(){
		button1=(Button)findViewById(R.id.review_main_copywater);
		button2=(Button)findViewById(R.id.review_main_query);
		button3=(Button)findViewById(R.id.review_main_upload);
		button4=(Button)findViewById(R.id.review_main_download);
		button1.setOnClickListener(this);
		button2.setOnClickListener(this);
		button3.setOnClickListener(this);
		button4.setOnClickListener(this);
		sp=new SharedPreferenceUtil(this);
		
	}

	@Override
	public void onClick(View v) {
		Intent intent=null;
		if(v.getId()==button1.getId()){
			intent=new Intent(ReviewMainActivity.this, ReviewDataActivity.class);
			startActivity(intent);
		}else if(v.getId()==button2.getId()){
			intent=new Intent(ReviewMainActivity.this, ReviewDataMainActivity.class);
			startActivity(intent);
		}else if(v.getId()==button4.getId()){
			ReviewDataDao dao=new ReviewDataDao(this);
			int k=dao.queryNoUpload();
		    int n=dao.queryNoCopyWater();
			dao.close();
			if(k>0){
				Toast.makeText(this, "还有没上传的复抄数据", 1000).show();
				return;
			}
		   if(n>0){
			   showDialog(DIALOG);
		   }else{
			   showDialog(DIALOG+1);
		   }
		}else if(v.getId()==button3.getId()){
			intent=new Intent(ReviewMainActivity.this, ReviewDataActivityUpload.class);
			startActivity(intent);
		}
		
	}
public class download extends AsyncTask<String, Integer, String>{
		
		public HttpClientServer server;
		
		public ProgressDialog dialog;
		
		public download(ProgressDialog dialog){
			this.dialog=dialog;
		}
		

		@Override
		protected String doInBackground(String... params) {

			  String userid=sp.getValue(XmlNameHelper.IMSI);
			
			  Map<String, String> map=new HashMap<String, String>();
			  map.put("imsi", userid);
			   String response=  server.doPost(map, params[0]);
			   System.out.println(response);
			   if(!response.equals("error")){
				   try {
					JSONObject obj=new JSONObject(response);
					//水表信息
					JSONArray waterinfo=obj.getJSONArray("waterinfo");
					
					int a=watertotal=waterinfo.length();
//					//表册信息
//					JSONArray waterlist=obj.getJSONArray("waterlist");
//					int b=waterlist.length();
					//用户信息
					JSONArray userinfo=obj.getJSONArray("userinfo");
					int c=userinfo.length();
					//月用水量信息
					JSONArray usewater=obj.getJSONArray("usewaterinfo");
					//工程单类型
					JSONArray ordertype=obj.getJSONArray("typeinfo");
					int d=usewater.length();
					int total=a+c+d;
		           publishProgress(total);			
					List<ContentValues> listwaterinfo=new ArrayList<ContentValues>();
					if(listwaterinfo!=null&&listwaterinfo.size()>0){
						for(int i=0;i<waterinfo.length();i++){
							JSONObject jb=waterinfo.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("waternumber", jb.getString("waternumber"));
							value.put("waterlistid", jb.getString("waterlistid"));
							value.put("usernumber", jb.getString("usernumber"));
							value.put("wateradds", jb.getString("wateradds"));
							if(jb.getString("alarmlimit").equals("null")){
								value.put("alarmlimit", 0.0);
							}else{
								value.put("alarmlimit", jb.getDouble("alarmlimit"));
							}
						
							if(jb.getString("lowalarmlimit").equals("null")){
								value.put("lowalarmlimit", 0.0);
							}else{
								value.put("lowalarmlimit", jb.getDouble("lowalarmlimit"));
							}
							
							
							String latitude=jb.getString("latitude");
							String rfidnumber=jb.getString("RFIDnumber");
							if(!rfidnumber.equals("null")){
								value.put("RFIDnumber", jb.getString("RFIDnumber"));
							}
							if(rfidnumber.equals("null")&&latitude.equals("null")){
								value.put("bandingstatus", "2");
							}else{
								value.put("bandingstatus", "3");
							}
							
							if(!latitude.equals("null")){
								value.put("latitude", jb.getDouble("latitude"));
							}
							String longitude=jb.getString("longitude");
							if(!longitude.equals("null")){
								value.put("longitude", jb.getDouble("longitude"));
							}
							String lastmonthwater=jb.getString("lastmonthwater");
							if(!lastmonthwater.equals("null")){
								value.put("lastmonthwater", jb.getDouble("lastmonthwater"));
							}else{
								value.put("lastmonthwater", 0.0);
							}
							
							value.put("metercaliber", jb.getString("metercaliber"));
							value.put("lastdate", jb.getString("lastdate"));
							value.put("iscopystatus", "未复抄");
							value.put("isupload", "0");	
							value.put("ismultiplecopy", "1");
							value.put("waterproperties", jb.getString("waterproperties"));
							value.put("sid", jb.getString("sid"));
							value.put("locationadds", jb.getString("addr"));
							publishProgress(i);
							listwaterinfo.add(value);
						}
					}
					
					
					List<ContentValues> listuserinfo=new ArrayList<ContentValues>();
					if(listuserinfo!=null&&listuserinfo.size()>0){
						for(int i=0;i<userinfo.length();i++){
							JSONObject jb=userinfo.getJSONObject(i);
							ContentValues value=new ContentValues();
							value.put("username", jb.getString("name"));
							value.put("usernumber", jb.getString("number"));
							value.put("phone", jb.getString("phone"));
							value.put("useradds", jb.getString("adds"));
							value.put("usertype", jb.getString("usertype"));
							value.put("userstatus", jb.getString("status"));
							value.put("ismultiplecopy", "1");
							listuserinfo.add(value);
							publishProgress(a+i);
						}
						
					}
					
					List<ContentValues> listusewater=new ArrayList<ContentValues>();
					if(listusewater!=null&&listusewater.size()>0){
						for(int i=0;i<usewater.length();i++){
							JSONObject js=usewater.getJSONObject(i);
							 ContentValues value=new ContentValues();
							 value.put("waternumber",js.getString("waternumber") );
							 value.put("month", js.getString("month"));
							 if(js.getString("watercount").equals("null")){
								 value.put("watercount",0);
							 }else{
								 value.put("watercount", js.getString("watercount"));
							 }
							 value.put("ismultiplecopy", "1");
							 listusewater.add(value);
							 publishProgress(a+c+i+1);
						}											
					}
					
					
					boolean b1=true;
					//b1=dao.insertALL(listwaterlist, DbTableName.WATERLIST);
					if(b1){
						b1=dao.insertALL(listuserinfo, DbTableName.USERINFO);
						if(b1){
							b1=dao.insertALL(listusewater, DbTableName.USEWATERINFO);
							if(b1){
								b1=dao.insertALL(listwaterinfo, DbTableName.WATERINFO);
							}
						}
					}
					
					dao.close();
					if(b1){
						return "success";
					}else{
						return "error";
					}
				} catch (JSONException e) {
					dao.close();
					System.out.println(e);
					e.printStackTrace();
				}
				   
			   }
			return "error";
			  
		  
		}

		@Override
		protected void onPreExecute() {
			server=new HttpClientServer(ReviewMainActivity.this);
			dao=new WaterListDaoImpl(ReviewMainActivity.this);
			
			dialog.setMax(100);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setTitle("下载数据中.......");
			dialog.setCancelable(false);
			dialog.show();
			
		}

	

		@Override
		protected void onProgressUpdate(Integer... values) {					    
			dialog.setProgress(values[0]);
		}

		@Override
		protected void onPostExecute(String result) {
			dao.close();
			dialog.cancel();
			System.out.println("result:"+result);
			if(TextUtils.isEmpty(result)){
				Toast.makeText(ReviewMainActivity.this, "下载失败", Toast.LENGTH_LONG).show();
			}else if(result.equals("error")){
				Toast.makeText(ReviewMainActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
			}
			else{
				
				Toast.makeText(ReviewMainActivity.this, "下载成功,共下载复抄数据:"+watertotal, Toast.LENGTH_LONG).show();
			}
			
			
		}
}

@Override
protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {
	case DIALOG:
		Builder builder = new android.app.AlertDialog.Builder(this);
		// 设置对话框的图标
		builder.setIcon(R.drawable.buttondraw);
		// 设置对话框的标题
		builder.setMessage("你还有未复查的数据！确定将下载新的数据原有的将会被删除！");

		// 添加一个确定按钮
		builder.setPositiveButton(" 确 定 ",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						ReviewDataDao dao=new ReviewDataDao(ReviewMainActivity.this);
						dao.delectReivew();
						dao.close();
						FileNameUtil f=new FileNameUtil(ReviewMainActivity.this);
						f.delectFile("ReviewImage");
					    ProgressDialog pd=new ProgressDialog(ReviewMainActivity.this);
					    download d=new download(pd);
					    d.execute(RequestUrl.REVIEWDOWNLOAD);
					}
				});

		builder.setNeutralButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		// 创建一个单选按钮对话框
		dialog = builder.create();
		break;
	case DIALOG + 1:
		Builder builder1 = new android.app.AlertDialog.Builder(this);
		// 设置对话框的图标
		builder1.setIcon(R.drawable.buttondraw);
		builder1.setMessage("确定下载新复抄数据？");
		builder1.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						ReviewDataDao dao=new ReviewDataDao(ReviewMainActivity.this);
						dao.delectReivew();
						dao.close();
						FileNameUtil f=new FileNameUtil(ReviewMainActivity.this);
						f.delectFile("ReviewImage");
						ProgressDialog pd=new ProgressDialog(ReviewMainActivity.this);
					    download d=new download(pd);
					    d.execute(RequestUrl.REVIEWDOWNLOAD);
					}
				});
		   builder1.setNeutralButton("取消",
				new android.content.DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}
				});
		// 创建一个单选按钮对话框
		dialog = builder1.create();
		break;
	}
	return dialog;
}

}
